<?php
/**
 * @file imagelibrary.php $
 * @author LiangJian (liangjian@haibao.com) $
 * @date 2015年8月3日 上午11:15:22 $
 * @brief APP图片库数据层 $
 */
namespace haibao\app\data;

use \haibao\frame\data\query\Condition;

class ImageLibrary extends \haibao\app\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\app\model\data\ImageLibrary');
    }
    
    public function getImageById($imageId, $brief = false){
        $result = $this->getOneById($imageId);
        $retArr = array('Id' => $imageId);
        $model = new \haibao\app\model\data\ImageLibrary();
        foreach($model->getKeyMap() as $keyName=>$keyType){
            $fieldName = $keyType->getFieldName();
            $retArr[$fieldName] = $result->$fieldName;
        }
        unset($result);
        if($brief){
            return $retArr;
        }
        $retArr['Star'] = $this->getStarByImageId($imageId);
        $retArr['Brand'] = $this->getBrandByImageId($imageId);
        $retArr['Fashion'] = $this->getFashionByImageId($imageId);
        $retArr['Area'] = $this->getAreaByImageId($imageId);
        $retArr['Event'] = $this->getEventByImageId($imageId);
        $retArr['Product'] = $this->getProductByImageId($imageId);
        
        return array_filter($retArr);
    }
    
    public function getImageByIds(array $imageIds,$brief = false){
        $imageList = array();
        if($imageIds){
            foreach ($imageIds as $key=>$imageId){
                $image = $this->getImageById($imageId,$brief);
                array_push($imageList, $image);
            }
        }
        return $imageList;
    }
    
    public function getImageLibraryByQuery($query){
        return $this->getAll($query);
    }
    
    public function saveImage($width, $height, $storagePath, $imageType, $userId, $upSource){
        $status = \haibao\app\model\data\ImageLibrary::STATUS_ENABLE;
        $imageId = $this->saveImageToMysql($width, $height, $storagePath, $imageType, $userId, $status, $upSource);
        
        return $imageId;
    }
    
    public function getImageByIdDownLoad($imageId){
    	$imageId = (array)$imageId;
    	$query = new \haibao\app\model\filter\ImageLibrary();
    	$query->where(\haibao\app\model\filter\ImageLibrary::CONDITION_FIELD_NAME_ID, Condition::CONDITION_IN, $imageId);
    	return $this->getAll($query);
    }
    
    /**
     * 保存图片信息到MySQL中
     */
    private function saveImageToMysql($width, $height, $storagePath, $imageType, $userId, $status, $upSource){
        $model = new \haibao\app\model\data\ImageLibrary();
        $model->Filename = $storagePath;
        $model->Width = $width;
        $model->Height = $height;
        $model->UpSource = $upSource;
        $model->Type = $imageType;
        $model->CreateBy = $userId;
        $model->CreateTime = new \DateTime();
        $model->Status = $status;
        $this->add($model);
    
        return $model->Id;
    }
    
    /**
     * 保存图片信息到APP库
     */
    public function addImageToApp($images,$typeFinal){
    	if(!$images){
    		return false;
    	}
    	$model = new \haibao\app\model\data\ImageLibrary();
    	$idArray = array();
    	foreach($images as $key=>$val){
    		$model->Filename = $val->Filename;
    		$model->Width = $val->Width;
    		$model->Height = $val->Height;
    		$model->UpSource = $val->UpSource;
    		$model->Type = $typeFinal;
    		$model->Description = $val->Description;
    		$model->CreateBy = $val->CreateBy;
    		$model->CreateTime = $val->CreateTime;
    		$model->Status = $val->Status;
    		$this->add($model);
    		array_push($idArray,$model->Id);
    	}
    	return $idArray;
    }
    
    /**
     * 保存单品库图片信息到APP商品库
     */
    public function addProductImageToApp($productInfo){
    	if(!$productInfo){
    		return false;
    	}
    	$model = new \haibao\app\model\data\ImageLibrary();
    	$productData = new \haibao\app\model\data\ProductImageProperty();
    	$imageBrandData = new \haibao\app\model\data\ImageBrand();
    	$imageIdArr = $imageInfoArr = array();
    	if(isset($productInfo) && $productInfo){
    		foreach($productInfo as $key=>$val){
    			$model->Filename = $val['FileName'];
    			$model->Width = $val['Width'];
    			$model->Height = $val['Height'];
    			$model->UpSource = 1;
    			$model->Type = \haibao\app\model\data\ImageLibrary::IMAGE_TYPE_PRODUCT;
    			$model->Description = $val['Description'];
    			$model->CreateBy = $val['CreateBy'];
    			$model->Status = $val['Status'];
    			$model->CreateTime = $val['CreateTime'];
    			$model->UpSource = $val['UpSource'];
    			$this->add($model);
    		
    			if($model->Id){
    				$productData->ImageId = $model->Id;
    				$productData->ProductName = $val['ProductName'];
    				$this->add($productData);
    				
    				$imageBrandData->ImageId = $model->Id;
    				$imageBrandData->BrandId = $val['BrandId'];
    				$this->add($imageBrandData);
    			}
    		}
    	}
    }
    
    /**
     * 根据filename查询一条图片信息
     */
    public function getOneImageByFile($fileName){
    	return $this->query("select Filename from ImageLibrary where Filename = %s", array($fileName))->fetch_assoc();
    }
    
    /**
     * 修改图片记录状态
     */
    public function updateImageStatus(array $idArr, $status = \haibao\app\model\data\ImageLibrary::STATUS_DISABLE){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $idArr));
        $sql = 'update `ImageLibrary` set Status=%s where id in (' . $str . ') limit %s';
        $aParam = $idArr;
        array_unshift($aParam, $status);
        array_push($aParam, count($idArr));
        
        $this->query($sql, $aParam);
    }
    
    /**
     * 修改图片详细信息
     * @param \haibao\app\model\data\ImageLibrary $model
     */
    public function updateImageLibrary($model){
        $this->beginTranscation();
        try {
            $idArr = (array)$model->Id;
            $str = preg_replace('/(\d+)/', '%s', implode(',', $idArr));
            $arrWhere = $aParam = array();
            if($idArr){
                $sql = 'update `ImageLibrary` set Description=' . $this->escape($model->Description) . ' where id in (' . $str . ')';
                $this->query($sql, $idArr);
            }
            
            if($model->ImageStar){
                $this->addImageStar($idArr, $model->ImageStar);
            } else {
            	$this->deleteImageStar($idArr);
            }
            if($model->ImageBrand){
                $this->addImageBrand($idArr, $model->ImageBrand);
            } else {
            	$this->deleteImageBrand($idArr);
            }
            if($model->ImageFashion){
                $this->addImageFashion($idArr, $model->ImageFashion);
            } else {
            	$this->deleteImageFashion($idArr);
            }
            if($model->ImageArea){
                $this->addImageArea($idArr, $model->ImageArea);
            } else {
            	$this->deleteImageArea($idArr);
            }
            if($model->ImageEvent){
            	$this->addImageEvent($idArr, $model->ImageEvent);
            }else {
            	$this->deleteImageEvent($idArr);
            }
            
            if($model->ProductName || $model->Price || $model->PriceType || $model->PriceSource){
                $this->addProductProperty($idArr, $model);
            } else {
            	$this->deleteProductProperty($idArr);
            }
        } catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
    }
    
    /**
     * 根据图片Id查询关联明星
     * @return int
     */
    public function getStarByImageId($imageId){
        $result = $this->query('select * from ImageStar where ImageId=%s', array($imageId));
        
        $retArr = array();
        while ($row = $result->fetch_assoc()){
            $starData = new \haibao\cms\data\Celebrity();
            $starObj = $starData->getCelebrityById($result->getData('StarId'));
            if( isset($starObj->NameCn) ){
                $row['StarName'] = $starObj->NameCn;
                $row['StarNameEn'] = $starObj->NameEn;
            } elseif( isset($starObj->NameEn) ){
            	$row['StarName'] = $starObj->NameEn;
            	$row['StarNameEn'] = $starObj->NameEn;
            }
            array_push($retArr, $row);
        }
        return $retArr;
    }
    
    /**
     * 根据图片Id查询关联品牌
     * @return int
     */
    public function getBrandByImageId($imageId){
        $result = $this->query('select BrandId from ImageBrand where ImageId=%s', array($imageId));
        
        $retArr = array();
        while ($row = $result->fetch_assoc()){
            $brandData = new \haibao\cms\data\Brand();
            $brandObj = $brandData->getBrandById($result->getData('BrandId'));
            if( isset($brandObj->NameCN) ){
                $row['BrandName'] = $brandObj->NameCN;
                $row['BrandNameEn'] = $brandObj->NameEN;
            }elseif( isset($brandObj->NameEN) ){
            	$row['BrandName'] = $brandObj->NameEN;
                $row['BrandNameEn'] = $brandObj->NameEN;
            }
            
            array_push($retArr, $row);
        }
        return $retArr;
    }
    
    /**
     * 根据图片Id查询服饰标签
     * @return int
     */
    public function getFashionByImageId($imageId){
        $result = $this->query('select b.Id,b.NameCN from ImageFashion as a left join FashionElement as b on a.FashionId=b.Id where ImageId=%s', array($imageId));
        
        $retArr = array();
        while ($row = $result->fetch_assoc()) {
            array_push($retArr, $row);
        }
        return $retArr;
    }
    
    /**
     * 根据图片ID查询所属地标
     * @return array
     */
    public function getAreaByImageId($imageId){
        $result = $this->query('select b.Id,b.Name from ImageArea as a left join Area as b on a.AreaId=b.Id where ImageId=%s', array($imageId));
        
        $retArr = array();
        while ($row = $result->fetch_assoc()){
            array_push($retArr, $row);
        }
        return $retArr;
    }
    
    /**
     * 根据图片Id查询图片事件
     */
    public function getEventByImageId($imageId){
    	$result = $this->query('select EventId from ImageEvent where ImageId=%s', array($imageId));
        
        $retArr = array();
        while ($row = $result->fetch_assoc()){
            $eventData = new \haibao\cms\data\Event();
            $eventObj = $eventData->getEventById($result->getData('EventId'));
            if( isset($eventObj->EventName) ){
            	
                $row['EventName'] = $eventObj->EventName;
            }
            
            array_push($retArr, $row);
        }
        return $retArr;
        
    }
    
    /**
     * 根据图片ID查询图片产品属性
     */
    public function getProductByImageId($imageId){
        $retArr = $this->query('select * from ProductImageProperty where ImageId=%s', array($imageId))->fetch_assoc();
        return $retArr;
    }
    
    /**
     * 根据用户ID查询3.0之前图片收藏记录
     */
    public function getCollectionById($userId,$currentPage,$pageSize){
    	$startCount = ($currentPage - 1) * $pageSize;
        $result = $this->query('select Filename from Collection where UserId=%s ORDER BY id DESC limit '.$startCount.','.$pageSize, array($userId));
        $retArr = array();
        while ($row = $result->fetch_assoc()) {
            array_push($retArr, $row);
        }
        return $retArr;
    }
    
    public function getUserHasCollection($userId){
    	$result = $this->query('select count(*) as Num from Collection where UserId=%s', array($userId));
    	$num = 0;
    	while($result->fetch_assoc()){
    		$num = $result->getData('Num');
    	}
    	if($num <= 1){
    		$num = 0;
    	}
    	return (int)$num;
    }
    
    /**
     * 添加图片与明星关联关系
     */
    private function addImageStar(array $idArr, array $starArr){
    	
        if(!$idArr || !$starArr){
            return false;
        }
        
        $this->deleteImageStar($idArr);
        
        $sql = 'insert into ImageStar(ImageId, StarId) values ';
        $arrSql = $arrValues = array();
        
        foreach($idArr as $imageId){
            foreach ($starArr as $starId){
                array_push($arrSql, '(%s,%s)');
                array_push($arrValues, $imageId);
                array_push($arrValues, $starId);
            }
        }
        
        if($arrSql && $arrValues){
            $sql .= implode(',', $arrSql);
            $this->query($sql, $arrValues);
        }
    }
    
    /**
     * 添加图片与品牌关联关系
     */
    private function addImageBrand(array $idArr, array $brandArr){
        if(!$idArr || !$brandArr){
            return false;
        }
        
        $this->deleteImageBrand($idArr);
        
        $sql = 'insert into ImageBrand(ImageId, BrandId) values ';
        $arrSql = $arrValues = array();
        
        foreach($idArr as $imageId){
            foreach ($brandArr as $brandId){
                array_push($arrSql, '(%s,%s)');
                array_push($arrValues, $imageId);
                array_push($arrValues, $brandId);
            }
        }
        
        if($arrSql && $arrValues){
            $sql .= implode(',', $arrSql);
            $this->query($sql, $arrValues);
        }
    }
    
    /**
     * 添加图片与服饰关联关系
     */
    private function addImageFashion(array $idArr, array $fashionArr){
        if(!$idArr || !$fashionArr){
            return false;
        }
        
        $this->deleteImageFashion($idArr);
        
        $sql = 'insert into ImageFashion(ImageId, FashionId) values ';
        $arrSql = $arrValues = array();
        
        foreach($idArr as $imageId){
            foreach ($fashionArr as $fashionId){
                array_push($arrSql, '(%s,%s)');
                array_push($arrValues, $imageId);
                array_push($arrValues, $fashionId);
            }
        }
        
        if($arrSql && $arrValues){
            $sql .= implode(',', $arrSql);
            $this->query($sql, $arrValues);
        }
    }
    
    /**
     * 添加图片与地标关联关系
     */
    private function addImageArea(array $idArr, array $areaArr){
        if(!$idArr || !$areaArr){
            return false;
        }
        
        $this->deleteImageArea($idArr);
        
        $sql = 'insert into ImageArea(ImageId, AreaId) values ';
        $arrSql = $arrValues = array();
        
        foreach($idArr as $imageId){
            foreach ($areaArr as $areaId){
                array_push($arrSql, '(%s,%s)');
                array_push($arrValues, $imageId);
                array_push($arrValues, $areaId);
            }
        }
        
        if($arrSql && $arrValues){
            $sql .= implode(',', $arrSql);
            $this->query($sql, $arrValues);
        }
    }
    
    /**
     * 添加图片与事件关联关系
     */
    private function addImageEvent(array $idArr, array $eventArr){
    	if(!$idArr || !$eventArr){
    		return false;
    	}

    	$this->deleteImageEvent($idArr);
    	
    	$sql = 'insert into ImageEvent(ImageId, EventId) values ';
    	$arrSql = $arrValues = array();
    	
    	foreach($idArr as $imageId){
    		foreach ($eventArr as $eventId){
    			array_push($arrSql, '(%s,%s)');
    			array_push($arrValues, $imageId);
    			array_push($arrValues, $eventId);
    		}
    	}
    	
    	if($arrSql && $arrValues){
    		$sql .= implode(',', $arrSql);
    		$this->query($sql, $arrValues);
    	}
    }
    
    /**
     * 添加商品属性
     * @param \haibao\app\model\data\ImageLibrary $model
     */
    private function addProductProperty(array $idArr, $model){
        $this->deleteProductProperty($idArr);
        
        $str = preg_replace('/(\d+)/', '%s', implode(',', $idArr));
        $sql = 'insert into ProductImageProperty(ImageId, ProductName, Price, PriceType, PriceSource) values ';
        $arrSql = $arrValues = array();
        
        foreach($idArr as $imageId){
            array_push($arrSql, '(%s,%s,%s,%s,%s)');
            array_push($arrValues, $imageId);
            array_push($arrValues, $model->ProductName);
            array_push($arrValues, $model->Price);
            array_push($arrValues, $model->PriceType);
            array_push($arrValues, $model->PriceSource);
        }
        if($idArr && $arrValues){
            $sql .= implode(',', $arrSql);
            $this->query($sql, $arrValues);
        }
    }
    
    /**
     * 删除图片与明星关联关系
     */
    private function deleteImageStar(array $idArr){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $idArr));
        $this->query('delete from ImageStar where ImageId in ('.$str.')', $idArr);
    }
    
    /**
     * 删除图片与品牌关联关系
     */
    private function deleteImageBrand(array $idArr){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $idArr));
        $this->query('delete from ImageBrand where ImageId in ('.$str.')', $idArr);
    }
    
    /**
     * 删除图片与服饰关联关系
     */
    private function deleteImageFashion(array $idArr){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $idArr));
        $this->query('delete from ImageFashion where ImageId in ('.$str.')', $idArr);
    }
    
    /**
     * 删除图片与地标关联关系
     */
    private function deleteImageArea(array $idArr){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $idArr));
        $this->query('delete from ImageArea where ImageId in ('.$str.')', $idArr);
    }
    
    /**
     * 删除图片与商品属性关联数据
     */
    private function deleteProductProperty(array $idArr){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $idArr));
        $this->query('delete from ProductImageProperty where ImageId in ('.$str.')', $idArr);
    }
    
    /**
     * 删除图片与地标关联数据
     */
    private function deleteImageEvent(array $idArr){
    	 $str = preg_replace('/(\d+)/', '%s', implode(',', $idArr));
        $this->query('delete from ImageEvent where ImageId in ('.$str.')', $idArr);
    }
    
}

